<template>
  <div py-16rpx>
    <nut-toast ref="toastRef" cover />
    <div v-if="isShow">
      <div v-if="couponList.length" @click.native="handleClickCoupon(item)" v-for="(item, index) in couponList"
        :key="index">
        <coupon :res="item" />
      </div>
      <div v-else mt-100rpx>
        <empty text="暂无优惠券" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getCouponList, receiveCoupons } from '@/api/promotion';
import coupon from '@/components/basic-template/coupon.vue';
import empty from '@/components/empty/index.vue';
import type { Search } from '@/constants/types';
import throttle from '@/utils/throttle';
import { onLoad, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app';
import type { ToastInst } from 'nutui-uniapp';
const searchForm = ref<Search>({
  pageNumber: 1,
  pageSize: 10,
})
const routerVal = ref<any>('')
const isShow = ref(false)
const couponList = ref<any>([])
const couponData = ref<any>('')
const toastRef = ref<ToastInst>()
function init() {
  isShow.value = false
  couponList.value = []
  searchForm.value.storeId = routerVal.value.storeId
  searchForm.value.pageNumber = 1
  fetchCoupon()

}
// 领取优惠券
async function handleClickCoupon(val: any) {
  console.log(val)
  throttle(() => {
    takeCoupon(val)
  }, 1500)
}


async function takeCoupon(val: any) {
  // toastRef.value?.showToast.loading('加载中...')
  
  try {
    toastRef.value?.showToast.loading('领取中...')
    const res = await receiveCoupons(val.id)
    toastRef.value?.hideToast()
    if (res.data.success) {
      
      uni.showToast({
        title: "领取成功",
        icon: "none"
      })
    }
  } catch (error) {
    toastRef.value?.hideToast()
  }

  
}

// 获取优惠券
async function fetchCoupon() {
  uni.stopPullDownRefresh();
  const res = await getCouponList(searchForm.value)
  isShow.value = true
  if (res.data.success) {
    couponList.value.push(...res.data.result.records)
    couponData.value = res.data.result
  }
}

onPullDownRefresh(() => {
  init()
})
onReachBottom(() => {
  if (couponData.value?.total > searchForm.value.pageNumber * searchForm.value.pageSize) {
    searchForm.value.pageNumber++;
    fetchCoupon()
  }
})

onLoad((options: any) => {
  routerVal.value = options
})
onMounted(() => {
  init();
})


</script>

<style scoped></style>
